package com.fenyin.samples.study.operation;

/**
 * 字节转换常用操作
 * 数据类型                            大小               范围                                                                                                                                        默认值 
 * --------------------------------------------------------------------------------------------------
 * byte 	         8位                 -128 - 127                                             0
 * short             2字节            -32768 - 32768                                         0
 * int               4字节            -2147483648 - 2147483648                               0
 * long              8字节            -9233372036854477808 - 9233372036854477808             0        
 * float             4字节            -3.40292347E+38 - 3.40292347E+38                       0.0f
 * double	         8字节            -1.79769313486231570E+308 - 1.79769313486231570E+308   0.0d
 * char              2字节           ‘ \u0000 - u\ffff ’                                    ‘\u0000 ’
 * boolean           1位                 true/false                                             false
 * --------------------------------------------------------------------------------------------------
 * @Author:fengzhichao
 * @Since:2012-12-17
 * @Version:1.1.0
 */
public class ByteTransfer {
	/**
	 * 将int转为低字节在前，高字节在后的byte数组
	 * @param n int
	 * @return byte[]
	 */
	public static byte[] toLH(int n) {
		byte[] b = new byte[4];
		b[0] = (byte) (n & 0xff);
		b[1] = (byte) (n >> 8 & 0xff);
		b[2] = (byte) (n >> 16 & 0xff);
		b[3] = (byte) (n >> 24 & 0xff);
		return b;
	}

	/**
	 * 将int转为高字节在前，低字节在后的byte数组
	 * @param n int
	 * @return byte[]
	 */
	public static byte[] toHH(int n) {
		byte[] b = new byte[4];
		b[3] = (byte) (n & 0xff);
		b[2] = (byte) (n >> 8 & 0xff);
		b[1] = (byte) (n >> 16 & 0xff);
		b[0] = (byte) (n >> 24 & 0xff);
		return b;
	}

	/**
	 * 将short转为低字节在前，高字节在后的byte数组
	 * @param n int
	 * @return byte[]
	 */
	public static byte[] toLH(short n) {
		byte[] b = new byte[2];
		b[0] = (byte) (n & 0xff);
		b[1] = (byte) (n >> 8 & 0xff);
		return b;
	}

	/**
	 * 将short转为高字节在前，低字节在后的byte数组
	 * @param n short
	 * @return byte[]
	 */
	public static byte[] toHH(short n) {
		byte[] b = new byte[2];
		b[1] = (byte) (n & 0xff);
		b[0] = (byte) (n >> 8 & 0xff);
		return b;
	}
	
	/**
     * 将float转为低字节在前，高字节在后的byte数组
     */ 
   public static byte[] toLH(float f) { 
     return toLH(Float.floatToRawIntBits(f)); 
   }  
    
   /**
     * 将float转为高字节在前，低字节在后的byte数组
     */ 
   public static byte[] toHH(float f) { 
     return toHH(Float.floatToRawIntBits(f)); 
   } 
   
   private static void print(byte[] result){
	   for(byte b:result){
		   System.out.print(b+"|");
	   }
	   System.out.println();
   }
   
   public static void main(String[] args){
        //将int转为低字节在前，高字节在后的byte数组
		print(toLH(-10));
	}

}
